<template>
  <common-list-group class="type-component-wrap" custom-right>
    <!-- 树结构 -->
    <div slot="group" class="group-list-component-wrap">
      <div class="group-header-wrap">
        <div class="group-header-title">资产类型</div>
      </div>
      <common-tree
          ref="treeRef"
          :isRequest="isRequest"
          search-placeholder="查询分类"
          node-key="id"
          :highlight-current="true"
          setNodeByKey="leaf"
          :is-slot="true"
          :tree-data="treeList"
          :treeLoading="treeLoading"
          :isShowIconForNoChild="true"
          :current-node-key="currentNodeKey"
          :hidden-index-icon="3"
          @handleNodeClick="handleNodeClick"
      >
        <div slot-scope="{ scope }" class="tree-item-wrap">
          <common-carousel-text :content="scope.data.name" :font-size="14"/>
          <el-popover
              trigger="hover"
              placement="right-start"
              width="150px"
              v-if="scope.node.level < 3 || scope.data.isDefault === 0"
          >
            <!--            <i slot="reference" class="iconfont icon-more"></i>-->
            <commonIcon iconName="icon-more" slot="reference" iconType="icon" :iconSize="16"></commonIcon>
            <common-menu>
              <common-menu-item
                  @click="treeAdd(scope.data)"
                  v-if="scope.node.level < 3"
              >新增子分类
              </common-menu-item
              >
              <common-menu-item
                  @click="scope.node.level > 3 ? edit(scope.data, 1) : treeEdit(scope.data)"
                  v-if="scope.node.level > 1 && scope.data.isDefault === 0"
              >编辑
              </common-menu-item
              >
              <common-menu-item
                  @click="scope.node.level > 3 ? handleDelete({categoryConfigId: scope.data.id}) : handleDeleteTree(scope.data.id)"
                  v-if="scope.node.level > 1 && scope.data.isDefault === 0"
              >删除
              </common-menu-item
              >
            </common-menu>
          </el-popover>
        </div>
      </common-tree>
    </div>
    <!-- 树结构弹框 -->
    <common-edit-dialog
        slot="custom_right"
        :title="`${isPopoverEdit ? '编辑' : '新增'}`"
        :visible="closePopover"
        @cancel="popoverCancel"
        @submit="popoverSubmit"
        :button-loading="popoverLoading"
        width="25%"
    >
      <el-form
          ref="popoverForm"
          :model="popoverForm"
          :rules="popoverFormRule"
          label-width="80px"
          @submit.native.prevent
      >
        <el-form-item label="分类名称" prop="name">
          <common-input
              :maxlength="20"
              v-model="popoverForm.name"
          ></common-input>
        </el-form-item>
        <el-form-item label="描述" prop="categoryDescribe">
          <common-input
              v-model="popoverForm.categoryDescribe"
              type="textarea"
          ></common-input>
        </el-form-item>
      </el-form>
    </common-edit-dialog>

    <!-- 资产分类列表查询区域 -->
     <template slot="custom_right" v-if="showType === 'indexList'">
      <base-group-list >
        <common-search slot="search" @search="handleQuery" @reset="resetQuery">
          <el-form
              :inline="true"
              ref="queryForm"
              :model="queryParams"
              label-width="95px"
          >
            <el-form-item label="资产类型名称" prop="categoryThirdName">
              <common-input
                  v-model="queryParams.categoryThirdName"
                  @enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="资产类型编码" prop="categoryThirdCode">
              <common-input
                  v-model="queryParams.categoryThirdCode"
                  @enter="handleQuery"
              />
            </el-form-item>
          </el-form>
        </common-search>
        <!-- 新增/删除按钮 -->
        <el-row slot="tools" :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                icon="el-icon-plus"
                plain
                @click="handleAdd"
                :disabled="tabLoading || treeLoading"
                v-hasPermi="['analysiscenter:assetCategory:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                icon="el-icon-delete"
                plain
                :disabled="!showBatch"
                @click="handleDelete()"
                v-hasPermi="['analysiscenter:assetCategory:remove']"
            >批量删除
            </el-button>
          </el-col>
        </el-row>
        <!-- 列表 -->
        <common-table
            v-loading="tabLoading"
            slot="content"
            :data="List"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="资产类型" prop="categorySecondCode" align="left">
            <template slot-scope="scope">
              <span>{{ scope.row.categorySecondCode }}</span>
            </template>
          </el-table-column>
          <el-table-column
              label="资产类型名称"
              prop="categoryThirdName"
              align="left"
          />
          <!-- <el-table-column
              label="资产类型编码"
              prop="categoryThirdCode"
              align="left"
          /> -->
          <el-table-column label="操作" align="left" width="125px">
            <template slot-scope="scope">
              <el-button type="text" @click="configure(scope.row)">配置</el-button>
              <el-button
                  type="text"
                  @click="edit(scope.row, 0)"
                  v-hasPermi="['analysiscenter:assetCategory:edit']"
              >编辑
              </el-button>
              <el-button
                  type="text"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['analysiscenter:assetCategory:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </common-table>
        <!-- 分页 -->
        <pagination
            v-show="total > 0"
            slot="pagination"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
      </base-group-list>
    </template>

    <!-- 右侧配置列表展示区域 -->
    <template slot="custom_right" v-else>
      <List :configure-view-id="configureId" :addConfigureParentId="addConfigureParentId" :label="label"></List>
    </template>

    <!-- 新增资产分类弹窗 -->
    <template v-if="isShowAdd" slot="custom_right">
      <add-assetsType
          ref="addAssetsType"
          @closeView="closeAdd"
          :isTitle="isTitle"
          @submitForm="AddSubmit"
          :assetsData="assetsTypeFormData"
      >
      </add-assetsType>
    </template>
    <!-- 配置详细页面 -->
    <template v-if="isShowConfigure" slot="custom_right">
      <add-configure
          ref="addConfigure"
          @close="closeConfigure"
          :configureViewId="configureId"
          :label="label"
      >
      </add-configure>
    </template>
  </common-list-group>
</template>

<script>
import BaseList from '@/mixins/BaseList'
import BaseGroupList from '@/template/components/BaseList'
import List from './components/components/list'
import addAssetsType from './components/add'
import addConfigure from './components/configure' // 1、引入
import {
  getTreeData,
  addTrees,
  editTrees,
  delTrees,
  assetsTypeList,
  assetsTypeDel,
  getInfoTrees,
  deleteForCheck,
  delTreesForCheck
} from '@/api/analysisCenter/assetsType'
import commonIcon from '@/components/CommonIcon'

export default {
  name: 'index',
  mixins: [BaseList],
  components: {
    addAssetsType,
    addConfigure, //2、注册
    commonIcon,
    BaseGroupList,
    List
  },
  data() {
    return {
      addConfigureParentId:'',
      showType: 'indexList',
      isRequest: false,
      currentNodeKey: '0',
      total: 0,
      groupData: [],
      assetsTypeFormData: {},
      assetsTypeId: null,
      configureId: null,
      isShowAdd: false,
      isTitle: false,
      isShowConfigure: false,
      queryParams: {
        parentId: null,
        categoryThirdName: null,
        categoryThirdCode: null,
        pageNum: 1,
        pageSize: 10
      },
      isEdit: false,
      isPopoverEdit: false,
      closePopover: false,
      popoverForm: {
        id: null,
        name: null,
        categoryDescribe: null,
        parentId: 0,
        categoryId: null,
        isDefault: 0
      },
      key: 'categoryConfigId',
      treeList: [],
      tabLoading: false,
      treeLoading: false,
      popoverLoading: false,
      List: [],
      popoverFormRule: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },

      rules: {
        categoryThirdName: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ],
        categoryThirdCode: [
          {
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          }
        ]
      },
      label: '',
      parentId: ''
    }
  },
  methods: {
    handleNodeClick(data) {
      // console.log(data)
      if (data.node.level === 4) {
        this.configureId = data.data.id
        this.showType = 'option'
        this.label = data.data.name
        this.addConfigureParentId = data.data.parentId
        // console.log("111",this.addConfigureParentId)
      } else {
        this.queryParams.pageNum = 1
        this.queryParams.pageSize = 10
        this.queryParams.parentId = data.node.level === 1 ? null : data.data.id
        this.parentId = data.node.level === 1 ? null : data.data.parentId
        this.getList()
        this.showType = 'indexList'
      }
    },
    AddSubmit() {
      this.isShowAdd = false
      this.getList()
      this.queryTree()
    },
    closeAdd() {
      //新增页面关闭
      this.isShowAdd = false
    },
    //查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    //重置
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    //资产列表
    getList() {
      this.tabLoading = true
      this.isRequest = true
      assetsTypeList(this.queryParams)
          .then((res) => {
            if (res && res.code === 200) {
              this.List = res.rows
              this.total = res.total
            } else {
              this.List = []
              this.total = 0
              this.handleListTips(res)
            }
          })
          .finally(() => {
            this.tabLoading = false
            this.isRequest = false
          })
    },
    //新增
    handleAdd() {
      this.isShowAdd = true
      this.isTitle = false
      this.assetsTypeFormData = { parentId: this.parentId, categoryId: this.queryParams.parentId}
    },
    //配置
    configure(row) {
      this.label = row.categoryThirdName
      this.isShowConfigure = true
      this.configureId = row.categoryConfigId
      // console.log(this.configureId)
    },
    closeConfigure() {
      this.isShowConfigure = false
    },
    //编辑
    edit(row, n) {
      //编辑id
      this.isShowAdd = true
      this.isTitle = true
      if(n === 0) {
        this.assetsTypeFormData = row
      } else {
        this.$nextTick(() => {
          this.$refs.addAssetsType.getInfoById(row.id)
        })
      }
    },
    //删除
    deleteData(row) {
      const ids = row?.categoryConfigId || this.ids.join(',')
      this.$GlobalDeleteConfirm().then(() => {
        assetsTypeDel({ ids }).then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage('删除成功')
            if (
                this.queryParams.pageNum > 1 &&
                ids.split(',').length === this.List.length
            ) {
              this.queryParams.pageNum -= 1
            }
            this.queryTree()
            this.getList()
          } else {
            this.$GlobalErrorConfirm('删除失败', res.msg)
          }
        })
      }).catch(()=>{});
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheck({ ids: ids })
            .then((res) => {
              if (res && res.code === 200) {
                resolve(res)
              } else {
                reject(res)
              }
            })
            .catch((err) => {
              reject(err)
            })
      })
    },
    //树节点取消
    popoverCancel() {
      this.closePopover = false
    },
    //树节点提交
    popoverSubmit() {
      this.$refs.popoverForm.validate((valid) => {
        if (valid) {
          this.popoverLoading = true
          if (this.isPopoverEdit) {
            editTrees(this.popoverForm)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage('编辑成功')
                    this.queryTree()
                    this.closePopover = false
                  } else {
                    this.$GlobalErrorConfirm('编辑失败', res.msg)
                  }
                })
                .finally(() => {
                  this.popoverLoading = false
                })
          } else {
            addTrees(this.popoverForm)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage('新增成功')
                    this.queryTree()
                    this.closePopover = false
                  } else {
                    this.$GlobalErrorConfirm('新增失败', res.msg)
                  }
                })
                .finally(() => {
                  this.popoverLoading = false
                })
          }
        }
      })
    },
    //树节点新增
    treeAdd(data) {
      this.popoverForm.name = ''
      this.popoverForm.categoryDescribe = ''
      this.popoverForm.id = ''
      this.popoverForm.categoryId = ''
      this.popoverForm.parentId = data.id
      this.isPopoverEdit = false
      this.closePopover = true
    },
    //树节点编辑
    treeEdit(data) {
      this.isPopoverEdit = true
      this.closePopover = true
      this.popoverForm.categoryId = data.id
      getInfoTrees({ categoryId: data.id }).then((res) => {
        if (res && res.code === 200) {
          this.popoverForm.id = res.data.id
          this.popoverForm.name = res.data.name
          this.popoverForm.parentId = res.data.parentId
          this.popoverForm.categoryDescribe = res.data.categoryDescribe
        } else {
          this.popoverForm.id = ''
          this.popoverForm.name = ''
          this.popoverForm.parentId = 0
          this.popoverForm.categoryDescribe = ''
        }
      })
    },
    //树节点删除
    deleteTreeData(id) {
      this.$GlobalDeleteConfirm().then(() => {
        delTrees({ ids: id })
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage('删除成功')
              } else {
                this.$GlobalErrorConfirm('删除失败', res.msg)
              }
            })
            .finally(() => {
              this.queryTree()
            })
      }).catch(()=>{});
    },
    // 树节点删除前校验
    beforeDeleteTreeForCheck(ids) {
      return new Promise((resolve, reject) => {
        delTreesForCheck({ ids: ids }).then((res) => {
          if (res && res.code === 200) {
            resolve(res)
          } else {
            reject(res)
          }
        })
      })
    },
    //树节点列表查询
    queryTree() {
      this.treeLoading = true
      getTreeData()
          .then((res) => {
            if (res && res.code === 200) {
              this.treeList = [
                {
                  name: '资产类别',
                  id: '0',
                  isDefault: 0, // 0 自定义
                  children: res.data
                }
              ]
              this.groupData = {
                categoryId: this.treeList[0].id,
                parentId: this.treeList[0].parentId,
                name: this.treeList[0].name
              }
            } else {
              this.treeList = []
              this.handleListTips(res)
            }
          })
          .finally((err) => {
            this.treeLoading = false
          })
    }
  },
  mounted() {
    this.getList()
    this.queryTree()
  }
}
</script>

<style scoped lang="scss">
.type-component-wrap {
  .group-header-wrap {
    height: 32px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .group-header-title {
      font-size: 14px;
    }
  }

  .tree-item-wrap {
    display: flex;
    align-items: center;
    width: 100%;

    &:hover {
      .iconfont {
        opacity: 1;
      }
    }

    .iconfont {
      opacity: 0;
      transition: opacity 0.15s linear;
    }
  }

  .el-tree-node__expand-icon {
    content: "\E63c";
    font-size: 18px;
  }
}
</style>
